﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CamlexNET;
using LifeInSharePoint.Common;
using LifeInSharePoint.Common.Base;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace LifeInSharePoint.Blog.Common.WebParts.LISPContactUs
{
    [ToolboxItemAttribute(false)]
    public class LISPContactUs : BaseWebPart
    {

        #region private variables

        private Table formTable;

        private HtmlGenericControl _containerDiv;
        private HtmlGenericControl _commentsDiv;
        private HtmlGenericControl _messageDiv;
        private InputFormTextBox _message;
        private TextBox _name;
        private RequiredFieldValidator _nameVal;
        private TextBox _subject;
        private RequiredFieldValidator _subjectVal;
        private TextBox _email;
        private RequiredFieldValidator _emailVal;
        private RequiredFieldValidator _messageVal;

        private Button _submitBooking;

        private const string STYLE_FORMTABLE = "lisp_formTable";
        private const string STYLE_BUTTON = "lisp_ButtonHeightWidth";
        private const string STYLE_BUTTONTABLE = "lisp_formtoolbar";
        private const string STYLE_BUTTONCELL = "lisp_toolbar";

        private const string COMMENTSLIST = "Contact";
        private const string CONTENTTYPE = "Life In SharePoint Blog Contact";
        private bool errorFound = false;
        private string errorMessage = null;

        #endregion


        #region public variables


        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [Category("Parameters")]
        [WebDisplayName("Form Button Text")]
        public string FormButtonText { get; set; }

        #endregion

        protected override void OnInit(EventArgs e)
        {
            this.ChromeType = PartChromeType.None;
            base.OnInit(e);
            FormButtonText = string.IsNullOrEmpty(FormButtonText) ? "Send Message" : FormButtonText;
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// CreateChildControls is where we need to instantiate all child controls 
        /// within our web part.
        /// </summary>
        /// 
        protected override void CreateChildControls()
        {
            if (!errorFound)
            {

                base.CreateChildControls();

                SPWebPartManager webPartManager = (SPWebPartManager)SPWebPartManager.GetCurrentWebPartManager(Page);

                _containerDiv = new HtmlGenericControl("div");
                _containerDiv.Attributes.Add("class", "contact-area");
                this.Controls.Add(_containerDiv);

                _messageDiv = new HtmlGenericControl("div");
                _containerDiv.Controls.Add(_messageDiv);
                _messageDiv.Visible = false;

                formTable = new Table();
                formTable.ID = "FormTable";
                formTable.Attributes.Add("class", STYLE_FORMTABLE);
                formTable.BorderWidth = 0;
                formTable.CellPadding = 0;
                formTable.CellSpacing = 0;
                formTable.EnableViewState = true;
                _containerDiv.Controls.Add(formTable);


                _name = new TextBox();
                _name.ID = "Name";
                _nameVal = new RequiredFieldValidator();
                _nameVal.ErrorMessage = "Please enter your name";
                _nameVal.ControlToValidate = _name.ID;
                SPFormHelper.AddLabelledRow(formTable, "Name", "", _name, _nameVal, null, false, webPartManager);

                _email = new TextBox();
                _email.ID = "Email";
                _emailVal = new RequiredFieldValidator();
                _emailVal.ErrorMessage = "Please enter your Email Address";
                _emailVal.ControlToValidate = _email.ID;
                SPFormHelper.AddLabelledRow(formTable, "Email", "", _email, _emailVal, null, false, webPartManager);


                _subject = new TextBox();
                _subject.ID = "Subject";
                _subjectVal = new RequiredFieldValidator();
                _subjectVal.ErrorMessage = "Please enter your message Subject";
                _subjectVal.ControlToValidate = _subject.ID;
                SPFormHelper.AddLabelledRow(formTable, "Subject", "", _subject, _subjectVal, null, false, webPartManager);


                _message = new InputFormTextBox();
                _message.ID = "Message";
                _message.Rows = 1;
                _message.Columns = 20;
                _message.TextMode = TextBoxMode.MultiLine;
                _message.RichText = false;

                _messageVal = new RequiredFieldValidator();
                _messageVal.ErrorMessage = "Please enter a message";
                _messageVal.ControlToValidate = _message.ID;
                SPFormHelper.AddRichTextRow(formTable, "Comment", null, _messageVal, null, _message, webPartManager);


                AddToolbarTable(this);


            }
            else
            {
                Label errorMsg = new Label();
                errorMsg.Text = errorMessage;
                this.Controls.Add(errorMsg);
            }

        }

        #region Helper Methods

        private void AddToolbarTable(System.Web.UI.WebControls.WebParts.WebPart part)
        {
            Table buttonTable = new Table();
            buttonTable.Attributes.Add("class", STYLE_BUTTONTABLE);
            buttonTable.CellPadding = 0;
            buttonTable.CellSpacing = 0;
            buttonTable.Attributes.Add("style", "margin-top: 7px;");

            _containerDiv.Controls.Add(buttonTable);

            _submitBooking = new Button();
            _submitBooking.Text = FormButtonText;
            _submitBooking.ID = "SendMessageButton";
            _submitBooking.Attributes.Add("class", STYLE_BUTTON);

            // hook up event handlers
            _submitBooking.Click += new EventHandler(_submitReplyButton_Click);

            TableRow row = new TableRow();
            buttonTable.Rows.Add(row);

            TableCell labelCell = new TableCell();
            labelCell.Attributes.Add("class", STYLE_BUTTONCELL);
            row.Cells.Add(labelCell);

            TableCell controlCell = new TableCell();
            controlCell.Attributes.Add("class", STYLE_BUTTONCELL);
            row.Cells.Add(controlCell);
            controlCell.ColumnSpan = 3;

            controlCell.Controls.Add(_submitBooking);
        }

        void _submitReplyButton_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(SubmitToList);
        }

        private void SubmitToList()
        {
            try
            {
                //Insert comment into comments list with current page id as reference.

                SPList contactList = SPContext.Current.Site.RootWeb.Lists["Comments"];
                SPListItem contact = contactList.Items.Add();


                contact["Title"] = _name.Text;
                contact["LISPContactEmail"] = _email.Text;
                contact["LISPContactSubject"] = _subject.Text;
                contact["LISPContactMessage"] = _message.Text;
                contact["LISPContactPosterIP"] = Context.Request.UserHostAddress;
                contact.Update();

                _messageDiv.Attributes.Add("class", "success");
                _messageDiv.Visible = true;
                _messageDiv.InnerHtml = "Message has been sent to us.  Thank you for your feedback and we will get back to you as soon as possible.";

            }
            catch (Exception ex)
            {
                _messageDiv.Attributes.Add("class", "error");
                _messageDiv.Visible = true;
                _messageDiv.InnerHtml = "There has been a problem sending your message.  Please try again later.";
                return;
            }
        }

        #endregion
    }
}

